
%let wrds = wrds.wharton.upenn.edu 4016;
options comamid=TCP remote=wrds;
signon username=_prompt_;
rsubmit;

options source nocenter ls=72 ps=max;

libname compx '/wrds/comp/sasdata/naa';
libname link '/wrds/crsp/sasdata/a_ccm';

* Date range-- applied to FYEAR ( Fiscal Year);
%let fyear1= 1975;
%let fyear2= 2010;

*  Selected data items (GVKEY, CUSIP, DATADATE, FYEAR and FYR are automatialy included);
%let vars= sich prcc_f csho at ceq sale dlc dltt;
%let out_ds= work.compx;

* Make extract set of Compustat Annual company data;
data comp1;
   set compx.funda(keep= gvkey cusip datadate fyear fyr &vars indfmt datafmt popsrc consol curcd);
   where fyear between &fyear1 and &fyear2;
   if indfmt='INDL' and datafmt='STD' and popsrc='D' and consol='C' and curcd='USD';
   drop indfmt datafmt popsrc consol curcd;  
run;

data link;
set link.ccmxpf_linktable;
if missing(lpermno) then delete;
if linkprim="P" or linkprim="C" then output;
run;

proc sort data=link nodup;
by gvkey lpermno;
run;

proc sql;
create table test as
select a.*, b.lpermno, b.linkprim, b.linkdt, b.linkenddt
from comp1 a, link b
where a.gvkey=b.gvkey and a.datadate >= b.linkdt and ((b.linkenddt=.E) or (a.datadate<=b.linkenddt));
quit;

proc sort data=test;
   by gvkey fyear;
run;

proc download data= test;
run;

endrsubmit;

proc export
  DATA=work.test
  OUTFILE="data\input\compannual.csv"
  DBMS=csv REPLACE;
run;
